package com.gjy.redis.util.struct;

import redis.clients.jedis.Jedis;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-14 15:37:38
 */
public class StringService {

    public void initStringData() {
        try (Jedis jedis = RedisConnection.getJedis()) {
            // 初始化20条string数据
            for (int i = 1; i <= 20; i++) {
                jedis.set("user:name:" + i, "User" + i);
                jedis.setex("user:token:" + i, 3600L, "token" + i);
                jedis.set("user:age:" + i, String.valueOf(20 + i));
            }
            System.out.println("String数据初始化完成");
        }
    }

    public void stringOperations() {
        try (Jedis jedis = RedisConnection.getJedis()) {
            // 基本操作
            jedis.set("string:test", "Hello Redis");
            System.out.println("GET string:test: " + jedis.get("string:test"));

            // 数值操作
            jedis.set("counter", "10");
            jedis.incr("counter");
            jedis.incrBy("counter", 5);
            System.out.println("INCR counter: " + jedis.get("counter"));

            // 字符串操作
            jedis.set("greeting", "Hello");
            jedis.append("greeting", " World");
            System.out.println("APPEND greeting: " + jedis.get("greeting"));

            // 截取字符串
            System.out.println("SUBSTR greeting: " + jedis.substr("greeting", 0, 4));

            // 批量获取
            System.out.println("MGET: " + jedis.mget("string:test", "counter", "greeting"));
        }
    }

    public void cleanup() {
        try (Jedis jedis = RedisConnection.getJedis()) {
            for (int i = 1; i <= 20; i++) {
                jedis.del("user:name:" + i);
                jedis.del("user:token:" + i);
                jedis.del("user:age:" + i);
            }
            for (int i = 1; i <= 5; i++) {
                jedis.del("batch:key:" + i);
            }
            jedis.del("string:test", "counter", "greeting");
        }
    }
}
